﻿@model Xms.Web.Models.FilterModel
@{
    Layout = null;
}
@{
    DialogModel dialogModel = ViewData["DialogModel"] as DialogModel;
}

<!--（Modal） -->
<div class="modal fade" id="filtersModal" tabindex="-1" role="dialog"
     aria-labelledby="filtersModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"
                        aria-hidden="true">
                    ×
                </button>
                <h4 class="modal-title" id="filtersModalLabel">
                    <span class="glyphicon glyphicon-filter"></span> @app.T["filter_condition"] - @Model.AttributeMeta.LocalizedName
                </h4>
            </div>
            <div class="modal-body">
                <div class="table-responsive" id="filterContainer">
                    <div class="form-group">
                        <div class="col-sm-3">
                            <select class="input-sm" name="conditionoperator"></select>
                        </div>
                        <div class="col-sm-9">
                            <input type="text" class="form-control input-sm" name="value" disabled="disabled" />
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="col-sm-12">
                            <label>
                                <input type="radio" name="logicaloperator" value="0" data-value="and" checked /> @app.T["filter_and"]
                            </label>
                            <label>
                                <input type="radio" name="logicaloperator" value="1" data-value="or" /> @app.T["filter_or"]
                            </label>
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="col-sm-3">
                            <select class="input-sm" name="conditionoperator"></select>
                        </div>
                        <div class="col-sm-9">
                            <input type="text" class="form-control input-sm" name="value" disabled="disabled" />
                        </div>
                    </div>
                    <script src="/content/js/jquery.form.js?v=@app.PlatformSettings.VersionNumber"></script>
                    <script>
                        function digitsValue(e){
                            var val=$(e).val();
                            var check=true;
                            var reg = new RegExp(/^\+?[1-9][0-9]*$/);
                            if(!reg.test(val)||val==''){
                                if($(e).next('label[name="digitsTip"]').length<=0){
                                    $('<label name="digitsTip">'+LOC_VALIDATION_DIGIT+'</label>').insertAfter($(e));
                                }
                                check=false;
                            }
                            else{
                                $(e).next('label[name="digitsTip"]').remove();
                                check=true;
                            }
                            return check;
                        }
                        var LOC_FILTER_CONDITION_OPERATOR_SELECT = '@app.T["filter_condition_operator_select"]';
                        var LOC_VALIDATION_DIGIT = '@app.T["validation_digit"]';
                        var FilterDialogModel = {
                            pageUrl: '@app.Url',
                            callback : @dialogModel.CallBack.IfEmpty("null"),
                            attributeName : '@Model.Field',
                            filter : @Html.Raw(Model.Filter != null ? Model.Filter.SerializeToJson(true) : "null"),
                            dialog : $('#filtersModal'),
                            operators : Xms.Fetch.ConditionOperators["@Model.DataType"],
                            datatype : "@Model.DataType",
                            attributeMetaDatas : @Html.Raw(Model.AttributeMeta.SerializeToJson()),
                            dialog_return: function () {
                                var digitscheck=true;
                                $('#filterContainer').find('input[name=value]').each(function(i,n){
                                    if($(n).attr('data-num')==true||$(n).attr('data-num')=='true'){
                                        digitscheck= digitsValue($(n));
                                        if(digitscheck==false){
                                            Xms.Web.Alert(false, LOC_VALUE_NOTVALID);
                                            return false;
                                        }
                                    }
                                });
                                if(digitscheck==false){
                                    return false;
                                }
                                var filter = new Xms.Fetch.FilterExpression();
                                $('#filterContainer').find('.form-group').each(function (i, n) {
                                    var row = $(n);
                                    var conditionoperator = Xms.Web.SelectedValue(row.find('select[name=conditionoperator]'));
                                    var logicaloperator = row.find('input[name=logicaloperator]:checked').val();
                                    //console.log(row,conditionoperator,logicaloperator);
                                    if (conditionoperator && conditionoperator != '') {
                                        var condition = new Xms.Fetch.ConditionExpression();
                                        condition.AttributeName = FilterDialogModel.attributeName;
                                        condition.Operator = parseInt(conditionoperator);
                                        var v = row.find('input[name=value]').attr('data-value') || row.find('input[name=value]').val();
                                        if(v && v != '') condition.Values.push(v);
                                        filter.Conditions.push(condition);
                                        //console.log(condition);
                                    }
                                    else if (logicaloperator) {
                                        filter.FilterOperator = parseInt(logicaloperator);
                                    }
                                });
                                console.log(filter);
                                if(typeof(FilterDialogModel.callback) == 'function'){
                                    FilterDialogModel.callback(FilterDialogModel.attributeName,filter);
                                }
                                Xms.Web.CloseDialog('#filtersModal');
                            },
                            bindSelected: function (result, inputid){
                                console.log(result,inputid);
                                $('#' + inputid).val(result[0].name);
                                $('#' + inputid).attr('data-value',result[0].id);
                            },
                            bindMoreSelected: function (result, inputid){
                                var rName='';
                                var rId='';
                                for(var i=0;i<result.length;i++){
                                    console.log(result,inputid);
                                    rName+=result[i].name;
                                    rId+=result[i].id;
                                    if(i!=result.length-1){
                                        rName+=',';
                                        rId+=',';
                                    }
                                }
                                $('#' + inputid).val(rName);
                                $('#' + inputid).attr('data-value',rId);
                            }
                        };
                        console.log(FilterDialogModel.attributeMetaDatas);
                        $(function () {
                            //console.log(1);
                            FilterDialogModel.dialog.modal({
                                keyboard: true
                            });
                            FilterDialogModel.dialog.on('hidden.bs.modal', function () {
                                Xms.Web.CloseDialog('#filtersModal');
                            });
                            //操作符
                            var op = new Array();
                            op.push('<option data-value="" value="">--'+LOC_FILTER_CONDITION_OPERATOR_SELECT+'--</option>');
                            $(FilterDialogModel.operators).each(function(i, n){
                                op.push('<option data-value="'+n[0]+'" value="'+n[1]+'">'+n[2]+'</option>');
                            });

                            //禁用输入框
                            var disabledArr=['Last7Days','LastWeek','LastMonth','LastYear','LastYear','NextWeek','NextMonth','NextYear','ThisWeek','ThisMonth','ThisYear','Today','Tomorrow','Yesterday'];
                            //显示时间控件
                            var showDatepicker=['Equal','NotEqual','GreaterThan','LessThan','GreaterEqual','LessEqual','OnOrAfter','OnOrBefore'];
                            //无需查找按钮
                            var noFindButton=['BeginsWith','DoesNotBeginWith','EndsWith','DoesNotEndWith','Like','NotLike'];
                            //需要下拉 多选
                            var moreSelect=[];
                            //包含和不包含
                            var includeNull=['NotNull','Null'];

                            //操作符改变事件
                            $('#filterContainer').find('select[name=conditionoperator]').each(function(i, n){
                                $(n).html(op.join('\n'));
                                $(n).bind('change', function(){
                                    var v = Xms.Web.SelectedValue($(this));
                                    var dataval=$(this).find('option:selected').attr('data-value');
                                    var id = FilterDialogModel.datatype + Math.round(new Date().getTime() / 1000);
                                    var input = $(this).parents('.form-group').find('input[name=value]');
                                    input.prop('id', id);
                                    if(v == Xms.Fetch.ConditionOperator.NotNull || v == Xms.Fetch.ConditionOperator.Null || v == null || v == ''||$.inArray(dataval,disabledArr)!=-1){
                                        if(input.parents('.typeahead__container').length>0){
                                            input.parents('.typeahead__container').replaceWith('<input type="text" class="form-control input-sm" name="value" disabled="disabled" >');
                                        }else{
                                            input.val('').prop('disabled','disabled');
                                        }
                                    }
                                    else if(v != null && v != ''){
                                        input.removeProp('disabled');
                                        //根据字段类型生成输入框
                                        switch(FilterDialogModel.datatype){
                                            case "lookup":
                                                if($.inArray(dataval,noFindButton)!=-1){
                                                    if(input.parents('.typeahead__container').length>0){
                                                        input.parents('.typeahead__container').replaceWith('<input type="text" class="form-control input-sm" name="value" >');
                                                    }else{
                                                        input.removeProp('disabled');
                                                    }
                                                }
                                                else if($.inArray(dataval,moreSelect)!=-1){
                                                    input.lookup({
                                                        dialog: function(){
                                                            Xms.Web.OpenDialog('/entity/RecordsDialog?entityid='+FilterDialogModel.attributeMetaDatas.referencedentityid+'&singlemode=true&inputid=' + id, 'FilterDialogModel.bindMoreSelected')
                                                        }
                                                        ,clear: function(){
                                                            $('#' + id).val('');
                                                            $('#' + id).siblings(':input').val('');
                                                        },
                                                        disabled:true
                                                    });
                                                }
                                                else{
                                                    input.lookup({
                                                        dialog: function(){
                                                            Xms.Web.OpenDialog('/entity/RecordsDialog?entityid='+FilterDialogModel.attributeMetaDatas.referencedentityid+'&singlemode=true&inputid=' + id, 'FilterDialogModel.bindSelected')
                                                        }
                                                        ,clear: function(){
                                                            $('#' + id).val('');
                                                            $('#' + id).siblings(':input').val('');
                                                        },
                                                        disabled:true
                                                    });
                                                }
                                                break;
                                            case "owner":
                                                if($.inArray(dataval,noFindButton)!=-1){
                                                    if(input.parents('.typeahead__container').length>0){
                                                        input.parents('.typeahead__container').replaceWith('<input type="text" class="form-control input-sm" name="value" >');
                                                    }else{
                                                        input.removeProp('disabled');
                                                    }
                                                }
                                                else if($.inArray(dataval,moreSelect)!=-1){
                                                    input.lookup({
                                                        dialog: function(){
                                                            Xms.Web.OpenDialog('/entity/RecordsDialog?entityid='+FilterDialogModel.attributeMetaDatas.referencedentityid+'&singlemode=true&inputid=' + id, 'FilterDialogModel.bindMoreSelected',null,function(){
                                                                input.removeProp('disabled');
                                                            })
                                                        }
                                                        ,clear: function(){
                                                            $('#' + id).val('');
                                                            $('#' + id).siblings(':input').val('');
                                                        },
                                                        disabled:true
                                                    });
                                                }
                                                else{
                                                    input.lookup({
                                                        dialog: function(){
                                                            Xms.Web.OpenDialog('/entity/RecordsDialog?entityid='+FilterDialogModel.attributeMetaDatas.referencedentityid+'&singlemode=true&inputid=' + id, 'FilterDialogModel.bindSelected',null,function(){
                                                                input.removeProp('disabled');
                                                            })
                                                        }
                                                        ,clear: function(){
                                                            $('#' + id).val('');
                                                            $('#' + id).siblings(':input').val('');
                                                        },
                                                        disabled:true
                                                    });
                                                }
                                                break;
                                            case "customer":
                                                input.lookup({
                                                    dialog: function(){
                                                        Xms.Web.OpenDialog('/entity/RecordsDialog?entityid='+FilterDialogModel.attributeMetaDatas.referencedentityid+'&singlemode=true&inputid=' + id, 'FilterDialogModel.bindSelected')
                                                    }
                                                    ,clear: function(){
                                                        $('#' + id).val('');
                                                        $('#' + id).siblings(':input').val('');
                                                    },
                                                    disabled:true
                                                });
                                                break;
                                            case "picklist":
                                                input.picklist({
                                                    displaytype: 'select'
                                                    , required: true
                                                    ,items: FilterDialogModel.attributeMetaDatas.optionset.items//[{value:0, text:'已提交'},{value:1, text:'审核中'}]
                                                });
                                                if($.inArray(dataval,moreSelect)!=-1){
                                                    input.siblings('select').prop('multiple','multiple');
                                                    input.siblings('select').prop('size',4);
                                                }
                                                else{
                                                    input.siblings('select').removeProp('multiple');
                                                    input.siblings('select').removeProp('size');
                                                }
                                                break;
                                            case "bit":
                                                input.picklist({
                                                    displaytype: 'select'
                                                    , required: true
                                                    ,items: FilterDialogModel.attributeMetaDatas.picklists//[{value:0, text:'否'},{value:1, text:'是'}]
                                                });
                                                break;
                                            case "datetime":
                                                input.unbind('keyup');
                                                input.removeAttr('data-num');
                                                if($.inArray(dataval,showDatepicker)!=-1){
                                                    input.addClass('datepicker');
                                                    $('.datepicker').datepicker({
                                                        autoclose: true
                                                        , clearBtn: true
                                                        , format: "yyyy-mm-dd"
                                                        , language: "zh-CN"
                                                    });
                                                }else{
                                                    input.removeClass('datepicker');
                                                    input.attr('data-num',true);
                                                    input.replaceWith(input.clone().bind('keyup',function(){digitsValue(this)}));
                                                }
                                                break;
                                            default:
                                                input.removeProp('disabled');
                                                break;
                                        }
                                    }
                                });
                            });

                            //绑定条件
                            if (FilterDialogModel.filter && FilterDialogModel.filter.Conditions&& FilterDialogModel.filter.Conditions.length > 0){
                                $('#filterContainer').find('input[name=logicaloperator][value='+FilterDialogModel.filter.FilterOperator+']').prop('checked',true);
                                var idx = 0;
                                $('#filterContainer').find('.form-group').each(function (i, n) {
                                    var row = $(n);
                                    if(row.find('select[name=conditionoperator]').length > 0){
                                        if(idx>=FilterDialogModel.filter.Conditions.length) return;
                                        var cd = FilterDialogModel.filter.Conditions[idx];
                                        if(FilterDialogModel.datatype == 'lookup' || FilterDialogModel.datatype == 'owner' || FilterDialogModel.datatype == 'customer'){
                                            Xms.Web.GetJson('/api/data/Retrieve/ReferencedRecord/' + FilterDialogModel.attributeMetaDatas.referencedentityid + '/' + cd.Values.join(',')
                                                ,null,function(response){
                                                    row.find('input[name=value]').val(response.content.name);
                                                });
                                        }
                                        else{
                                            row.find('input[name=value]').val(cd.Values.join(','));
                                        }
                                        row.find('input[name=value]').attr('data-value',cd.Values.join(','));
                                        row.find('select[name=conditionoperator] option[value='+cd.Operator+']').prop('selected',true).trigger('change');

                                        idx++;
                                    }
                                });
                            }
                        });
                    </script>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default"
                        data-dismiss="modal">
                    <span class="glyphicon glyphicon-remove"></span>
                    @app.T["dialog_close"]
                </button>
                <button type="button" class="btn btn-primary" onclick="FilterDialogModel.dialog_return()">
                    <span class="glyphicon glyphicon-ok"></span>
                    @app.T["dialog_ok"]
                </button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div><!-- /.modal -->